<script setup name="area-select">
import { provide } from 'vue';

const props = defineProps({
  hasNext: {
    type: Boolean,
    required: true,
  },
  modelValue: {
    type: Array,
    required: true,
  },
});

const emits = defineEmits([
  'select',
  'focus',
  'blur',
  'change',
  'update:modelValue',
]);

const el = ref(null);

// 上下文
provide('emits', emits);

let record = [];
function pushRecord(newValue) {
  record.push(newValue);
}
provide('pushRecord', pushRecord);

const visible = ref(false);

function onFocus() {
  // 打开下拉框
  visible.value = true;
  emits('focus');
  record = [];
}

function onBlur() {
  visible.value = false;
  emits('blur');
}

watch(
  () => props.hasNext,
  (newValue) => {
    if (!newValue) {
      emits('change', record);
      emits('update:modelValue', record);
      el.value.blur();
    }
  },
);

</script>

<template>
  <div
    ref="el"
    class="area-select"
    tabindex="0"
    @focus="onFocus"
    @blur="onBlur"
  >
    <span
      v-for="(value, i) in props.modelValue"
      :key="i"
    >
      {{ value }}
    </span>
    <i-ep-arrow-down class="icon" />
    <div
      v-show="visible"
      class="popup"
    >
      <slot />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.area-select {
  color: #333;
  display: inline-flex;
  align-items: center;
  padding: 4px;
  border: 1px solid #e2e2e2;
  cursor: pointer;
  user-select: none;
  position: relative;

  >span {
    margin-right: 4px;
  }

  .icon {
    font-size: 12px;
    margin: 0 4px;
  }

  .popup {
    position: absolute;
    top: 100%;
    left: 0;
    width: 550px;
    background-color: #fff;
    border: 1px solid #e2e2e2;
    z-index: 1;
    padding: 8px;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
  }
}
</style>
